package com.dhh.sky.widget;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import com.dhh.sky.R;
import com.dhh.sky.model.SkyDriveObject;
import com.dhh.sky.util.CUtil;
import com.dhh.sky.util.Constant;
import com.dhh.sky.util.FileManager;

import android.content.Context;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class TransitionTabDownloadAdapter extends BaseAdapter {
	private LayoutInflater inflater;
	private FileManager fm;
    private List<FileItem> fis;
	private String director = Environment.getExternalStorageDirectory().getPath();
	
	public TransitionTabDownloadAdapter(Context context){
		inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		fm = new FileManager(context);
    	fis = new ArrayList<FileItem>();
		loadFiles();
	}
	
	private void loadFiles(){
		File file = new File(director+"/SkyDrive");
		for(File f : file.listFiles()){
			if(f.isFile()){
				FileItem item = new FileItem(f.getName(),f.getName());
				String id = CUtil.getFilePreName(f.getName());
				SkyDriveObject obj = fm.getFile(id);
				if(obj!=null){
					item.setShowName(obj.getName());
				}
				
				fis.add(item);
			}
		}
	}

	@Override
	public int getCount() {
		return fis.size();
	}

	@Override
	public FileItem getItem(int position) {
		if(position>=fis.size() || position<0){
			return null;
		}else{
			return fis.get(position);
		}
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View view = inflater.inflate(R.layout.transition_manage_item,parent,false);
		final FileItem item = this.getItem(position);
		ImageView icon = (ImageView) view.findViewById(R.id.mli_icon);
		TextView name = (TextView) view.findViewById(R.id.mli_name);
		if(Constant.pictureFileType.contains(CUtil.getFileExtesion(item.getShowName()))){
			File file = new File(director+"/SkyDrive/"+item.getFileName());
			icon.setImageBitmap(CUtil.decodeBitmap(file, 160, 160));
		}else{
			icon.setImageResource(SkyDriveObject.getFileIcon(CUtil.getFileExtesion(item.getShowName())));
		}
		name.setText(item.getShowName());
		
		return view;
	}
	

	
	private class FileItem{
		private String fileName;
		private String showName;	
		
		public FileItem(String fileName,String showName){
			this.fileName = fileName;
			this.showName = showName;
		}
		
		public String getFileName() {
			return fileName;
		}
		
		public void setFileName(String fileName) {
			this.fileName = fileName;
		}
		
		public String getShowName() {
			return showName;
		}
		public void setShowName(String showName) {
			this.showName = showName;
		}	
		
	}
}
